import asyncio

import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
import os

from semantic_kernel.connectors.search_engine import BingConnector
from semantic_kernel.core_plugins import WebSearchEnginePlugin, TimePlugin
from semantic_kernel.planners import SequentialPlanner


async def run_function(*args):
    return await kernel.invoke(*args)

if __name__ == "__main__":
    os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY_ZHIHU"]
    os.environ["OPENAI_BASE_URL"] = os.environ["OPENAI_API_BASE_ZHIHU"]
    os.environ["BING_API_KEY"] = "903a3284d484407591c2af8dad032770"

    service_id = "web_search_service"
    kernel = sk.Kernel()

    HuggingFaceChatCompletion
    service = OpenAIChatCompletion(service_id=service_id,api_key=os.environ.get("OPENAI_API_KEY_ZHIHU"),ai_model_id="gpt-4")
    kernel.add_service(service=service)

    connector = BingConnector(api_key=os.environ["BING_API_KEY"])
    kernel.add_plugin(WebSearchEnginePlugin(connector),"WebSearch")
    kernel.add_plugin(TimePlugin(),"time")

    planner = SequentialPlanner(kernel,service_id)
    query = "周杰伦2024墨尔本演唱会是星期几？"

    plan = asyncio.run(planner.create_plan(goal=query))
    result = asyncio.run(plan.invoke(kernel))

    for i,step in enumerate(plan.steps):
        print(step.description)
        print(step.plugin_name + "." + step.name, end=":")
        print(step.parameters)
        print(step._outputs[0] + "=" + str(result.metadata["results"][i].value))

    print(f"Agent回复：{result}")
